<template>
  <view class="plan-create-container">
    <!-- 自定义导航栏 -->
    <cu-custom bgColor="bg-gradual-green" :isBack="true">
      <block slot="content">创建生产计划</block>
      <block slot="right">
        <text class="cuIcon-check" @click="savePlan"></text>
      </block>
    </cu-custom>

    <!-- 表单内容 -->
    <view class="form-container">
      <!-- 基本信息 -->
      <view class="form-section bg-white margin-top">
        <view class="section-header padding">
          <text class="section-title">基本信息</text>
        </view>
        <view class="form-content padding">
          <view class="form-item margin-bottom">
            <text class="form-label required">计划名称</text>
            <input v-model="planForm.name" 
                   placeholder="请输入计划名称" 
                   class="form-input" />
          </view>
          
          <view class="form-item margin-bottom">
            <text class="form-label">计划描述</text>
            <textarea v-model="planForm.description" 
                      placeholder="请输入计划描述" 
                      class="form-textarea"></textarea>
          </view>
          
          <view class="form-item margin-bottom">
            <text class="form-label required">关联订单</text>
            <picker :range="orderOptions" 
                    range-key="name"
                    :value="selectedOrderIndex"
                    @change="onOrderChange">
              <view class="form-picker">
                {{ planForm.orderId ? (orderOptions[selectedOrderIndex] && orderOptions[selectedOrderIndex].name) : '请选择订单' }}
                <text class="cuIcon-right"></text>
              </view>
            </picker>
          </view>
          
          <view class="form-item margin-bottom">
            <text class="form-label required">优先级</text>
            <picker :range="priorityOptions" 
                    range-key="label"
                    :value="selectedPriorityIndex"
                    @change="onPriorityChange">
              <view class="form-picker">
                {{ planForm.priority ? (priorityOptions[selectedPriorityIndex] && priorityOptions[selectedPriorityIndex].label) : '请选择优先级' }}
                <text class="cuIcon-right"></text>
              </view>
            </picker>
          </view>
        </view>
      </view>

      <!-- 时间安排 -->
      <view class="form-section bg-white margin-top">
        <view class="section-header padding">
          <text class="section-title">时间安排</text>
        </view>
        <view class="form-content padding">
          <view class="form-item margin-bottom">
            <text class="form-label required">计划开始时间</text>
            <picker mode="datetime" 
                    :value="planForm.startTime" 
                    @change="onStartTimeChange">
              <view class="form-picker">
                {{ planForm.startTime || '请选择开始时间' }}
                <text class="cuIcon-right"></text>
              </view>
            </picker>
          </view>
          
          <view class="form-item margin-bottom">
            <text class="form-label required">计划结束时间</text>
            <picker mode="datetime" 
                    :value="planForm.endTime" 
                    @change="onEndTimeChange">
              <view class="form-picker">
                {{ planForm.endTime || '请选择结束时间' }}
                <text class="cuIcon-right"></text>
              </view>
            </picker>
          </view>
          
          <view class="form-item margin-bottom">
            <text class="form-label">预计工时</text>
            <input v-model="planForm.estimatedHours" 
                   type="number"
                   placeholder="请输入预计工时" 
                   class="form-input" />
          </view>
        </view>
      </view>

      <!-- 产品信息 -->
      <view class="form-section bg-white margin-top">
        <view class="section-header padding">
          <text class="section-title">产品信息</text>
          <text class="cuIcon-add section-action" @click="addProduct"></text>
        </view>
        <view class="form-content">
          <view v-for="(product, index) in planForm.products" :key="index" 
                class="product-item padding border-bottom">
            <view class="product-header flex justify-between align-center margin-bottom-sm">
              <text class="product-title">产品 {{ index + 1 }}</text>
              <text class="cuIcon-delete text-red" @click="removeProduct(index)"></text>
            </view>
            
            <view class="product-form">
              <view class="form-row flex gap-sm margin-bottom-sm">
                <view class="form-item flex-sub">
                  <text class="form-label">产品名称</text>
                  <input v-model="product.name" 
                         placeholder="请输入产品名称" 
                         class="form-input" />
                </view>
                <view class="form-item" style="width: 200rpx;">
                  <text class="form-label">数量</text>
                  <input v-model="product.quantity" 
                         type="number"
                         placeholder="数量" 
                         class="form-input" />
                </view>
              </view>
              
              <view class="form-row flex gap-sm margin-bottom-sm">
                <view class="form-item flex-sub">
                  <text class="form-label">规格型号</text>
                  <input v-model="product.specification" 
                         placeholder="请输入规格型号" 
                         class="form-input" />
                </view>
                <view class="form-item flex-sub">
                  <text class="form-label">单位</text>
                  <input v-model="product.unit" 
                         placeholder="单位" 
                         class="form-input" />
                </view>
              </view>
              
              <view class="form-item">
                <text class="form-label">备注</text>
                <textarea v-model="product.remark" 
                          placeholder="请输入备注信息" 
                          class="form-textarea small"></textarea>
              </view>
            </view>
          </view>
          
          <view v-if="planForm.products.length === 0" class="empty-products padding text-center">
            <text class="text-gray">暂无产品，点击右上角添加</text>
          </view>
        </view>
      </view>

      <!-- 工艺流程 -->
      <view class="form-section bg-white margin-top">
        <view class="section-header padding">
          <text class="section-title">工艺流程</text>
          <text class="cuIcon-add section-action" @click="addProcess"></text>
        </view>
        <view class="form-content">
          <view v-for="(process, index) in planForm.processes" :key="index" 
                class="process-item padding border-bottom">
            <view class="process-header flex justify-between align-center margin-bottom-sm">
              <text class="process-title">工序 {{ index + 1 }}</text>
              <view class="process-actions">
                <text v-if="index > 0" class="cuIcon-up margin-right" @click="moveProcess(index, -1)"></text>
                <text v-if="index < planForm.processes.length - 1" class="cuIcon-down margin-right" @click="moveProcess(index, 1)"></text>
                <text class="cuIcon-delete text-red" @click="removeProcess(index)"></text>
              </view>
            </view>
            
            <view class="process-form">
              <view class="form-row flex gap-sm margin-bottom-sm">
                <view class="form-item flex-sub">
                  <text class="form-label">工序名称</text>
                  <input v-model="process.name" 
                         placeholder="请输入工序名称" 
                         class="form-input" />
                </view>
                <view class="form-item" style="width: 200rpx;">
                  <text class="form-label">工种</text>
                  <picker :range="workTypeOptions" 
                          :value="process.workTypeIndex"
                          @change="onWorkTypeChange(index, $event)">
                    <view class="form-picker small">
                      {{ process.workType || '选择工种' }}
                      <text class="cuIcon-right"></text>
                    </view>
                  </picker>
                </view>
              </view>
              
              <view class="form-row flex gap-sm margin-bottom-sm">
                <view class="form-item flex-sub">
                  <text class="form-label">预计工时</text>
                  <input v-model="process.estimatedHours" 
                         type="number"
                         placeholder="工时" 
                         class="form-input" />
                </view>
                <view class="form-item flex-sub">
                  <text class="form-label">所需人数</text>
                  <input v-model="process.requiredWorkers" 
                         type="number"
                         placeholder="人数" 
                         class="form-input" />
                </view>
              </view>
              
              <view class="form-item">
                <text class="form-label">工序要求</text>
                <textarea v-model="process.requirements" 
                          placeholder="请输入工序要求和注意事项" 
                          class="form-textarea small"></textarea>
              </view>
            </view>
          </view>
          
          <view v-if="planForm.processes.length === 0" class="empty-processes padding text-center">
            <text class="text-gray">暂无工序，点击右上角添加</text>
          </view>
        </view>
      </view>

      <!-- 备注信息 -->
      <view class="form-section bg-white margin-top margin-bottom">
        <view class="section-header padding">
          <text class="section-title">备注信息</text>
        </view>
        <view class="form-content padding">
          <textarea v-model="planForm.remark" 
                    placeholder="请输入备注信息" 
                    class="form-textarea"></textarea>
        </view>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="bottom-actions">
      <button class="cu-btn bg-gray margin-right" @click="saveDraft">保存草稿</button>
      <button class="cu-btn bg-green" @click="savePlan">创建计划</button>
    </view>
  </view>
</template>

<script>
import mesApi from '../../../api/mes'

export default {
  data() {
    return {
      planForm: {
        name: '',
        description: '',
        orderId: '',
        priority: '',
        startTime: '',
        endTime: '',
        estimatedHours: '',
        products: [],
        processes: [],
        remark: ''
      },
      orderOptions: [],
      selectedOrderIndex: 0,
      priorityOptions: [
        { label: '低优先级', value: 'low' },
        { label: '中优先级', value: 'medium' },
        { label: '高优先级', value: 'high' }
      ],
      selectedPriorityIndex: 1,
      workTypeOptions: ['切割', '组装', '打包', '质检', '喷涂', '焊接']
    }
  },

  onLoad() {
    this.loadOrders()
  },

  methods: {
    async loadOrders() {
      try {
        const response = await mesApi.order.getList()
        this.orderOptions = response.data
      } catch (error) {
        // 模拟数据
        this.orderOptions = [
          { id: 1, name: '订单WK001 - 铝合金门窗', orderNo: 'WK001' },
          { id: 2, name: '订单WK002 - 塑钢窗户', orderNo: 'WK002' },
          { id: 3, name: '订单WK003 - 防盗门', orderNo: 'WK003' }
        ]
      }
    },

    onOrderChange(e) {
      this.selectedOrderIndex = e.detail.value
      this.planForm.orderId = this.orderOptions[e.detail.value].id
    },

    onPriorityChange(e) {
      this.selectedPriorityIndex = e.detail.value
      this.planForm.priority = this.priorityOptions[e.detail.value].value
    },

    onStartTimeChange(e) {
      this.planForm.startTime = e.detail.value
    },

    onEndTimeChange(e) {
      this.planForm.endTime = e.detail.value
    },

    addProduct() {
      this.planForm.products.push({
        name: '',
        quantity: '',
        specification: '',
        unit: '',
        remark: ''
      })
    },

    removeProduct(index) {
      this.planForm.products.splice(index, 1)
    },

    addProcess() {
      this.planForm.processes.push({
        name: '',
        workType: '',
        workTypeIndex: 0,
        estimatedHours: '',
        requiredWorkers: 1,
        requirements: ''
      })
    },

    removeProcess(index) {
      this.planForm.processes.splice(index, 1)
    },

    moveProcess(index, direction) {
      const newIndex = index + direction
      if (newIndex >= 0 && newIndex < this.planForm.processes.length) {
        const temp = this.planForm.processes[index]
        this.planForm.processes.splice(index, 1)
        this.planForm.processes.splice(newIndex, 0, temp)
      }
    },

    onWorkTypeChange(processIndex, e) {
      const workTypeIndex = e.detail.value
      this.planForm.processes[processIndex].workTypeIndex = workTypeIndex
      this.planForm.processes[processIndex].workType = this.workTypeOptions[workTypeIndex]
    },

    validateForm() {
      if (!this.planForm.name.trim()) {
        uni.showToast({
          title: '请输入计划名称',
          icon: 'none'
        })
        return false
      }

      if (!this.planForm.orderId) {
        uni.showToast({
          title: '请选择关联订单',
          icon: 'none'
        })
        return false
      }

      if (!this.planForm.priority) {
        uni.showToast({
          title: '请选择优先级',
          icon: 'none'
        })
        return false
      }

      if (!this.planForm.startTime) {
        uni.showToast({
          title: '请选择开始时间',
          icon: 'none'
        })
        return false
      }

      if (!this.planForm.endTime) {
        uni.showToast({
          title: '请选择结束时间',
          icon: 'none'
        })
        return false
      }

      if (new Date(this.planForm.startTime) >= new Date(this.planForm.endTime)) {
        uni.showToast({
          title: '结束时间必须晚于开始时间',
          icon: 'none'
        })
        return false
      }

      if (this.planForm.products.length === 0) {
        uni.showToast({
          title: '请至少添加一个产品',
          icon: 'none'
        })
        return false
      }

      if (this.planForm.processes.length === 0) {
        uni.showToast({
          title: '请至少添加一个工序',
          icon: 'none'
        })
        return false
      }

      return true
    },

    async savePlan() {
      if (!this.validateForm()) return

      try {
        uni.showLoading({ title: '创建中...' })
        
        await mesApi.productionPlan.create({
          ...this.planForm,
          status: 'active'
        })
        
        uni.showToast({
          title: '创建成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
      } catch (error) {
        console.error('创建失败:', error)
        uni.showToast({
          title: '创建失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    async saveDraft() {
      try {
        uni.showLoading({ title: '保存中...' })
        
        await mesApi.productionPlan.create({
          ...this.planForm,
          status: 'draft'
        })
        
        uni.showToast({
          title: '草稿保存成功',
          icon: 'success'
        })
        
      } catch (error) {
        console.error('保存失败:', error)
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.plan-create-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.form-section {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
  
  .section-header {
    border-bottom: 1rpx solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .section-action {
      font-size: 32rpx;
      color: #1890ff;
    }
  }
  
  .form-item {
    .form-label {
      display: block;
      font-size: 28rpx;
      color: #333;
      margin-bottom: 16rpx;
      
      &.required::after {
        content: '*';
        color: #f5222d;
        margin-left: 4rpx;
      }
    }
    
    .form-input {
      width: 100%;
      height: 80rpx;
      padding: 0 24rpx;
      border: 1rpx solid #d9d9d9;
      border-radius: 8rpx;
      font-size: 28rpx;
    }
    
    .form-textarea {
      width: 100%;
      min-height: 120rpx;
      padding: 16rpx;
      border: 1rpx solid #d9d9d9;
      border-radius: 8rpx;
      font-size: 28rpx;
      resize: none;
      
      &.small {
        min-height: 80rpx;
      }
    }
    
    .form-picker {
      height: 80rpx;
      padding: 0 24rpx;
      border: 1rpx solid #d9d9d9;
      border-radius: 8rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #333;
      
      &.small {
        height: 60rpx;
        font-size: 24rpx;
      }
    }
  }
  
  .form-row {
    .form-item {
      margin-bottom: 0;
    }
  }
}

.product-item,
.process-item {
  .product-header,
  .process-header {
    .product-title,
    .process-title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
    }
    
    .process-actions {
      display: flex;
      align-items: center;
      
      .cuIcon-up,
      .cuIcon-down,
      .cuIcon-delete {
        font-size: 28rpx;
        color: #999;
        
        &.text-red {
          color: #f5222d;
        }
      }
    }
  }
}

.empty-products,
.empty-processes {
  color: #999;
  font-size: 28rpx;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  padding: 24rpx;
  border-top: 1rpx solid #f0f0f0;
  display: flex;
  gap: 24rpx;
  
  .cu-btn {
    flex: 1;
  }
}
</style>
